# coding = 'utf-8'
import requests
import csv
import random
import time
import socket
import http.client
# import urllib.request
import os
from bs4 import BeautifulSoup  # 用来代替正则式取源码中相应标签中的内容


def get_content(url, data=None):
    header = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'zh-CN,zh;q=0.8',
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'
    }
    timeout = random.choice(range(80, 100))
    while True:
        try:
            rep = requests.get(url, headers=header, timeout=timeout)
            rep.encoding = 'utf-8'
            # req = urllib.request.Request(url, data, header)
            # response = urllib.request.urlopen(req, timeout=timeout)
            # html1 = response.read().decode('UTF-8', errors='ignore')
            # response.close()
            break
            # except urllib.request.HTTPError as e:
            #         print( '1:', e)
            #         time.sleep(random.choice(range(5, 10)))
            #
            # except urllib.request.URLError as e:
            #     print( '2:', e)
            #     time.sleep(random.choice(range(5, 10)))
        except socket.timeout as e:
            print('3', e)
            time.sleep(random.choice(range(8, 15)))

        except socket.error as e:
            print('4', e)
            time.sleep(random.choice(range(20, 60)))

        except http.client.BadStatusLine as e:
            print('5', e)
            time.sleep(random.choice(range(20, 40)))

        except http.client.IncompleteRead as e:
            print('6', e)
            time.sleep(random.choice(range(30, 50)))

    return rep.text


def get_data(html_text):
    final = []
    bs = BeautifulSoup(html_text, "html.parser")
    body = bs.body
    data = body.find('div', {'id': '7d'})   # # 找到id为7d的div
    ul = data.find('ul')    # 获取url部分信息
    li = ul.find_all('li')  # 获取所有的li
    for day in li:
        temp = []
        date = day.find('h1').string
        temp.append(date)
        inf = day.find_all('p')
        temp.append(inf[0].string, )
        if inf[1].find('span') is None:
            temperature_highest = None  # 天气预报可能没有当天的最高气温（到了傍晚，就是这样），需要加个判断语句,来输出最低气温
        else:
            temperature_highest = inf[1].find('span').string
            temperature_highest = temperature_highest.replace('C', '')
        temperature_lowest = inf[1].find('i').string  # 找到最低温
        temperature_lowest = temperature_lowest.replace('℃', '')  # 最低温度后面有个℃，去掉这个符号
        temp.append(temperature_highest)  # 将最高温添加到temp中
        temp.append(temperature_lowest)  # 将最低温添加到temp中
        final.append(temp)  # 将temp加到final中
    return final


def write_data(data, name):
    file_name = name
    if os.path.exists(file_name):
        os.remove(file_name)

    with open(file_name, 'a', errors='ignore', newline='') as f:
        f_csv = csv.writer(f)
        f_csv.writerows(data)
        print("Write file Success: " + file_name)


if __name__ == '__main__':
    url = 'http://www.weather.com.cn/weather/101010100.shtml' # 北京
    # url = 'http://www.weather.com.cn/weather/101190401.shtml' # 苏州
    # url = 'http://www.weather.com.cn/weather/101240901.shtml'   # 萍乡
    html = get_content(url)
    result = get_data(html)
    write_data(result, '../output/weather.csv')